<template>
  <h1>用户登录</h1>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
        <van-field 
            v-model="form.userName" 
            label="用户名" 
            name="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]" 
        />
        <van-field 
            type="password"
            v-model="form.passWord" 
            label="密码" 
            name="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]" 
        />
        <div class="btn">
            <van-button native-type="submit" type="primary" block round >提交</van-button>
        </div>
    </van-cell-group>
  </van-form>
</template>

<script setup>
import { reactive, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'

// 获取当前vue实例
const { proxy } = getCurrentInstance()
const router = useRouter()

const form = reactive({
    userName: '',
    passWord: ''
})
const onSubmit = async () => {
    // async...await... 让异步过程看起来像同步
    const { data } = await proxy.$api.login(form)
    console.log(data)
    if (data.code === 10000) {
        // 将服务器端返回的数据存储到本地
        localStorage.setItem('h5_token', data.data.token)
        localStorage.setItem('h5_userInfo', JSON.stringify(data.data.userInfo))
        router.push('/home')
    }
}
</script>

<style scoped lang="less">
h1 {
    text-align: center;
}
.btn {
    font-size: 16px;
}
</style>
